<?php

/*
 * Fresns Control Panel (Standalone)
 * Copyright (C) 2021-Present 刘鑫
 * Released under the MIT License.
 */

namespace App\Plugins\FcpApi\TweetConfigs;

use App\Base\Services\BaseAdminService;
use App\Http\Center\Helper\CmdRpcHelper;
use App\Http\FresnsApi\Helpers\ApiConfigHelper;
use App\Http\FresnsCmd\FresnsCmdWordsConfig;
use App\Http\FresnsDb\FresnsPlugins\FresnsPlugins;
use App\Plugins\FcpApi\TweetFiles\TweetFiles;
use App\Plugins\FcpApi\TweetLanguages\TweetLanguages;
use App\Plugins\FcpApi\TweetMemberRoles\TweetMemberRoles;
use App\Plugins\FcpApi\TweetPlugin\TweetPlugin;
use App\Plugins\FcpApi\TweetPlugin\TweetPluginConfig;
use Illuminate\Support\Facades\DB;

class FsService extends BaseAdminService
{
    public function __construct()
    {
        $this->model = new FsModel();
        $this->resource = FsResource::class;
        $this->resourceDetail = FsResourceDetail::class;
    }

    public function common()
    {
        $common = parent::common();

        $common['sitePrivatePluginOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_MODE);
        $common['sitePrivateEndOption'] = FsConfig::SITE_PRIVATE_END_OPTION;
        $common['siteOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_SITE);
        $common['emailOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_EMAIL);
        $common['smsOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_SMS);
        $common['iosOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_IOS);
        $common['androidOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_ANDROID);
        $common['wechatOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_WECHAT);
        $common['imageOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_FILE);
        $common['videoOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_FILE);
        $common['audioOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_FILE);
        $common['fileOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_FILE);
        $common['registerOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_REGISTER);
        $common['verificationOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_VERIFICATION);
        $common['mapOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PLUGINS_MAP);
        $common['manyUsersOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::MANY_USERS);
        $common['proveOption'] = TweetPlugin::buildSelectOptionsByUnikey(TweetPluginConfig::PROVE);
        //获取对应的七大洲编号
        $continents = self::getItemValueArrByItemKey(FsConfig::CONTINENTS);
        $continentsArr = [];
        foreach ($continents as $v) {
            $item = [];
            $item['key'] = $v['id'];
            $item['text'] = $v['name'];
            $continentsArr[] = $item;
        }
        //获取地图服务商
        $mapArr = self::getItemValueArrByItemKey('maps');
        $commonMapArr = [];
        foreach ($mapArr as $v) {
            $item = [];
            $item['key'] = $v['id'];
            $item['text'] = $v['name'];
            $commonMapArr[] = $item;
        }
        $common['mapServiceOption'] = $commonMapArr;
        $common['continentOption'] = $continentsArr;
        //获取语言代码
        $languageArr = self::getItemValueArrByItemKey(FsConfig::LANGUAGE_CODES);
        foreach ($languageArr as &$language) {
            $language['name_desc'] = $language['name'].' - '.$language['localName'].' > '.$language['code'];
        }
        $common['languageOption'] = $languageArr;
        //获取地区代码
        $areasArr = self::getItemValueArrByItemKey(FsConfig::AREAS);

        foreach ($areasArr as &$area) {
            $area['name_desc'] = $area['name'].' - '.$area['localName'].' > '.$area['code'];
        }
        $common['areasOption'] = $areasArr;
        $common['dateOption'] = FsConfig::DATE_OPTION;
        $common['lengthUnitsOption'] = FsConfig::LENGTHUNITS_OPTION;

        $common['memberRoleOption'] = TweetMemberRoles::staticBuildSelectOptions();
        $languageArr = TweetConfigService::getLanguageStatus();
        $common['language_status'] = $languageArr['language_status'];
        $common['default_language'] = $languageArr['default_language'];
        $common['languagesOption'] = $languageArr['languagesOption'];

        $utcArr = self::getItemValueArrByItemKey(FsConfig::UTC);
        $commonUtcArr = [];
        foreach ($utcArr as $v) {
            $item = [];
            $item['key'] = $v['value'];
            $item['text'] = $v['value'];
            $commonUtcArr[] = $item;
        }
        $common['defaultTimezoneOption'] = $commonUtcArr;
        //钱包货币
        $currencyCodesArr = self::getItemValueArrByItemKey(FsConfig::CURRENCY_CODES);

        $commonCurrencyCodesArr = [];
        foreach ($currencyCodesArr as $v) {
            $item = [];
            $item['key'] = $v['code'];
            $name = $v['name'];
            $item['text'] = $v['code']."($name)".' --> '.$v['ctryName'];
            $commonCurrencyCodesArr[] = $item;
        }

        $common['walletCurrencyCodeOption'] = $commonCurrencyCodesArr;

        return $common;
    }

    //获取对应的地区编号
    public static function getItemValueArrByItemKey($itemKey)
    {
        $configs = FsModel::where('item_key', $itemKey)->value('item_value');

        $contentArr = json_decode($configs, true);

        return $contentArr ?? [];
    }

    public function updateConfigs($configArr)
    {
        // dd($configArr);
        $updateArr = [];
        foreach ($configArr as $v) {
            foreach ($v['dict_item_arr'] as $i) {
                $item = [];
                if (! empty($i['lang_json'])) {
                    DB::table('languages')->where('table_name', TweetConfigsConfig::CFG_TABLE)->where('table_key', $i['alias_key'])->delete();
                    $langArr = $i['lang_json'];
                    $itemArr = [];
                    foreach ($langArr as $lang) {
                        $item = [];
                        $item['table_name'] = TweetConfigsConfig::CFG_TABLE;
                        $item['table_field'] = 'item_value';
                        $item['table_key'] = $i['alias_key'];
                        $item['lang_tag'] = $lang['key'];
                        $item['lang_content'] = $lang['lang_content'] ?? null;
                        $itemArr[] = $item;
                    }
                    TweetLanguages::insert($itemArr);
                }

                $item = [];
                $item['item_key'] = $i['alias_key'];
                $value = $i['item_value'] ?? null;
                if ($i['item_type'] == 'checkbox' || $i['item_type'] == 'select') {
                    if (! empty($i['item_value'])) {
                        if (is_array($i['item_value'])) {
                            $value = implode(',', $i['item_value']);
                        } else {
                            $value = $i['item_value'];
                        }
                    }
                }

                if (is_bool($value)) {
                    if ($value == true) {
                        $value = 'true';
                    } else {
                        $value = 'false';
                    }
                }
                $item['is_multilingual'] = 0;
                if (! empty($i['lang_json'])) {
                    $item['is_multilingual'] = 1;
                }

                // if($i['alias_key'] == 'comment_limit_whitelist' || $i['alias_key'] == 'post_limit_whitelist'){
                //     $value = json_encode($i['item_value']);
                // }
                if (! empty($i['item_value'])) {
                    if (is_array($i['item_value'])) {
                        $value = json_encode($i['item_value']);
                    }
                }

                $item['item_value'] = $value ?? null;
                $updateArr[] = $item;
            }
        }

        $model = new FsModel();

        if ($updateArr) {
            $model->updateBatch($updateArr);
        }
    }

    public function packStore($langTag, $langTagArr, $packArr)
    {
        foreach ($packArr as $v) {
            $langTagNameArr[] = $v['name'];
        }

        $nameArr = [];
        foreach ($langTagArr as $value) {
            if (! in_array($value['name'], $langTagNameArr)) {
                $item = [];
                $item['name'] = $value['name'];
                $item['canDelete'] = 'false';
                $nameArr[] = $item;
            }
        }

        $packArr = array_merge($nameArr, $packArr);

        $packJson = json_encode($packArr);
        $count = FsModel::where('item_key', 'language_pack')->count();
        if ($count > 0) {
            FsModel::where('item_key', 'language_pack')->update(['item_value' => $packJson]);
        } else {
            $input = [
                'item_key' => 'language_pack',
                'item_value' => $packJson,
            ];
            FsModel::where('item_key', 'language_pack')->insert($input);
        }

        $langTagMap = [];
        foreach ($langTagArr as $value) {
            $langTagMap[$value['name']] = $value['content'];
        }

        $addLangTagArr = [];
        foreach ($packArr as $v) {
            $item = [];
            $item['name'] = $v['name'];
            $item['content'] = $langTagMap[$v['name']] ?? null;
            $addLangTagArr[] = $item;
        }

        $count = FsModel::where('item_key', $langTag)->count();
        $addLangTagJson = json_encode($addLangTagArr);
        if ($count > 0) {
            FsModel::where('item_key', $langTag)->update(['item_value' => $addLangTagJson]);
        } else {
            $input = [
                'item_key' => $langTag,
                'item_value' => $addLangTagJson,
            ];

            FsModel::insert($input);
        }

        return true;
    }

    public static function getImageSignUrlByFileId($fileId)
    {
        //判断是否开启防盗链
        $imageStatus = ApiConfigHelper::getConfigByItemKey('images_url_status');
        $files = TweetFiles::where('id', $fileId)->first();

        $imagesHost = ApiConfigHelper::getConfigByItemKey('images_bucket_domain');
        $imagesConfig = ApiConfigHelper::getConfigByItemKey('images_thumb_config');
        if ($imageStatus == true) {
            $uuid = $files['uuid'];
            $cmd = FresnsCmdWordsConfig::FRESNS_CMD_ANTI_LINK_IMAGE;
            $input['fid'] = $uuid;
            $resp = CmdRpcHelper::call(FresnsPlugins::class, $cmd, $input);
            if (CmdRpcHelper::isErrorCmdResp($resp)) {
                return false;
            }

            return $resp['output']['imageConfigUrl'];
        } else {
            return $imagesHost.$files['file_path'].$imagesConfig;
        }
    }
}
